package demo;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.halo.trade.data.sina.Level2Handler;
import org.halo.trade.data.sina.SinaLevel2Fetcher;

public class SinaLevel2Deamon {
	
	private static SinaLevel2Deamon deamon = new SinaLevel2Deamon();
	
	private SinaLevel2Deamon(){
		
	}
	public static SinaLevel2Deamon getInstance(){
		return deamon;
	}
	//固定的线程池子
	private static ThreadPoolExecutor exec = new ThreadPoolExecutor(8, 8, 0L,
			TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(100000),
			new ThreadPoolExecutor.CallerRunsPolicy());

	public void start(List<String> symbols, Level2Handler level2_handler,int fetch_type) {
		List<String> indexsymbols = new ArrayList<>();
		// 启动多线程，进行数据的处理。
		SinaLevel2Fetcher ui_level2_fetcher = new SinaLevel2Fetcher(fetch_type, symbols, indexsymbols,
				level2_handler, null);
		ui_level2_fetcher.setName(symbols.get(0));
		exec.execute(ui_level2_fetcher);
	}
	
	public void stop(String symbolsName){
		if(symbolsName == null){
			return;
		}
		try{
	    List<Runnable> fetcherList = new ArrayList<Runnable>();
	    BlockingQueue<Runnable> queueList = exec.getQueue();
	    fetcherList.addAll(queueList);
		for(Runnable runnable : fetcherList){
			SinaLevel2Fetcher fetcher = (SinaLevel2Fetcher)runnable;
			String threadName = fetcher.getName();
			if(threadName.equals(symbolsName)){
				fetcher.closeThread();
				break;
			}
		}
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}

}
